$(function() {
	const $pop10 = $('.pop_window10');
	var two_;
	var addressOne; //小区编码
	var supermarketId; //超市ID
    var url = 'http://www.laykj.cn/wherebuyAPI/';//"http://192.168.0.100:8080/wherebuyAPI/";
    if (window.location.href.indexOf('laykj.cn') > -1) {
        url = 'http://www.laykj.cn/wherebuyAPI/'
    } else if (window.location.href.indexOf('http://192.168.0.6/') > -1) {
        url = 'http://192.168.0.6:8080/wherebuyAPI/'
    } else {
        url = 'http://192.168.0.100:8080/wherebuyAPI/'
    }

    //返回
	$(".member_fanhui").click(function() {
		window.location.href = "member_info_authentication.html";
	});

	//身份证正面
	var $file = $("#idcard_front");
	$file.change(function() {
		two_ = 0;
		loadImg("#idcard1", "#idcard_front", "#idcardf");
	});

	//身份证反面
	var $file1 = $("#idcard_back");
	$file1.change(function() {
		two_ = 1;
		loadImg("#idcard2", "#idcard_back", "#idcardb");
	});

	function loadImg(divid, inputid, imgid) {
		//获取文件
		var animateimg = $(inputid).val();
		var imgarr = animateimg.split('\\'); //分割
		var myimg = imgarr[imgarr.length - 1]; //去掉 // 获取图片名
		var houzui = myimg.lastIndexOf('.'); //获取 . 出现的位置
		var ext = myimg.substring(houzui, myimg.length).toUpperCase(); //切割后缀，大写
		var file = $(divid).find("input")[0].files[0];
		if (file !== undefined) {
			if (ext != '.PNG' && ext != '.GIF' && ext != '.JPG' && ext != '.JPEG' && ext != '.BMP') {
				toolTip_box('文件类型错误<br>请上传正确的图片类型');
				return;
			} else {
				$file.next().css({
					visibility: 'hidden'
				});
				error_img = false;
				if (two_ == 1) error_img2 = false;
				//创建读取文件的对象
				var reader = new FileReader();

				//创建文件读取相关的变量
				var imgFile;

				//为文件读取成功设置事件
				reader.onload = function(e) {

					imgFile = e.target.result;

					$(imgid).attr('src', imgFile);
				};
				//正式读取文件
				reader.readAsDataURL(file);
			}
		} else {
			toolTip_box('请上传身份证正反面照片');
			error_img = true;
		}
	}

	// 提交验证
	var error_user = true;
	var error_phone = true;
	var error_ress = true;
	var error_img = true;
	var error_img2 = true;
	var $useryzm = $('#user_name'); //check名字
	var $phone = $('#phone'); //check phone
	var $detailed_add = $('#detailed_add'); //详细地址
	$useryzm.blur(function() { //chack姓名
		check_yzm();
	});

	function check_yzm() {
		var val = $useryzm.val();
		var re = /^[^ ]+$/;
		if (val.length > 0 && re.test(val)) {
			error_user = false;
		} else {
			toolTip_box('请输入正确的姓名');
			error_user = true;
		}
	}

	$phone.blur(function() { //check电话
		check_phone();
	});

	function check_phone() {
		var val = $phone.val();
		var re = /^1[3-9][0-9]\d{8}$/;

		if (re.test(val)) {
			error_phone = false;
		} else {
			toolTip_box('请输入正确的11位手机号');
			error_phone = true;
		}
	}

	$detailed_add.blur(function() { //chack详细地址
		check_detailed_add();
	});

	function check_detailed_add() {
		var detailed_addval = $detailed_add.val();
		if (detailed_addval.length > 0 && detailed_addval.length < 60) {
			error_detailed_add = false;
		} else {
			toolTip_box('请输入详细的单元楼门牌号');
			error_detailed_add = true;
		}
	}
	// 表单提交
	$('.card_ok').click(function() {
		if (error_user == false && error_phone == false && error_detailed_add == false && error_ress == false && error_img == false && error_img2 == false) {
			var formData = new FormData();
			var user = $useryzm.val();
			var mibiles = $phone.val();
			var addresstwo = $trigger1.val() + $detailed_add.val();
			var idcard = document.getElementById("idcard_front").files[0];
			var idcard2 = document.getElementById("idcard_back").files[0];
			formData.append("realName", user);
			formData.append("mobile", mibiles);
			formData.append("areaCode", addressOne);
			formData.append("address", addresstwo);
			formData.append("supermarketId", supermarketId);
			formData.append("file", idcard);
			formData.append("file", idcard2);
			var xhr = new XMLHttpRequest();
			$pop10.children().text("正在上传图片0% ，请稍等").end().show();
			xhr.upload.onprogress = function(e){//加载事件
				$pop10.children().text("正在上传图片"+parseInt((e.loaded/e.total)*100)+"% ，请稍等");
				if(e.loaded / e.total==1){
					$pop10.hide();
					xhr.onload = function () {
						if (JSON.parse(xhr.response).respCode === "S") {
							tipsBox('已经提交至系统审核<br>稍后会以短信的方式通知您')
						} else {
							if (JSON.parse(xhr.response).errorCode === 1906) {
								window.location.href = '../register/login.html'
							} else {
								toolTip_box(JSON.parse(xhr.response).errorMsg)
							}
						}
					}
				};
			}
			xhr.onerror = function () {
				toolTip_box('上传失败,可能网络已经掉线');
			}
			xhr.open("post",url+"user/authentication/applyProcurer.do",true);//请求参数
			xhr.setRequestHeader('accessToken', $.cookie('accessToken'));
			xhr.send(formData);
		} else {
			toolTip_box("请正确输入所有信息");
		}
	});

	//收货地址弹框
	const address_xuan = $('.address_xuan');
	const sheng = address_xuan.children().eq(0);
	const address_view = $(".address_view");
	const address_con = $(".address_con");
	const $trigger1 = $("#trigger1");

	//拿省
	$trigger1.click(function() {
		document.activeElement.blur();//去除焦点
		address_con.show().children().animate({top: 0});
		new ajax({
			url: 'area/area/getArea.do',
			type: 'post',
			contentType: 'application/json;charset=utf-8',
			dataType: 'json',
			data: JSON.stringify({
				parent: '1000'
			}),
			success: function(data) {
				if (data.respCode != "S") {
					var lis = $(`<p>${"请重新登录"}<em></em></p>`);
					lis.appendTo(sheng);
					return;
				}
				sheng.empty()
				for (let i = 0; i < data.data.length; i++) {
					var li = $(`<p>${data.data[i].name}<em>${data.data[i].code}</em></p>`);
					li.appendTo(sheng);
				}
			}
		})
	});


	//关闭
	$(".address_con img").click(function() {
		var this_ = $(this).parent().parent();
		this_.children().animate({
				top: "33.35rem"
			},
			function() {
				this_.hide().children().eq(1).children().empty().hide().eq(0).show().end().end().end().eq(0).children().text("");
			});
	});
	$(".Supermarket_con img").click(function() {
		var this_ = $(this).parent().parent();
		this_.children().animate({
				top: "33.35rem"
			},
			function() {
				this_.hide();
			});
	});
	//拿市，区，街，小区
	address_xuan.delegate('p', 'click', function(e) {
		var this_ = $(this);
		var parent = this_.children().text();
		var ix = parseInt(this_.parent().index());
		let areaCode = ''
		//contents() 查找匹配元素内部所有的子节点（包括文本节点)过滤掉子节点
		var contstr = this_.contents().filter(function(index, content) {
			return content.nodeType === 3;
		}).text();
		address_view.children().eq(ix).text(contstr).nextAll().text("");
		if (ix < 3) {
			this_.parent().nextAll().empty();
			new ajax({
				url: 'area/area/getArea.do',
				type: 'post',
				contentType: 'application/json;charset=utf-8',
				dataType: 'json',
				data: JSON.stringify({
					parent: parent
				}),
				success: function(data) {
					console.log(data);
					if (data.respCode != "S") {
						return;
					}
					this_.parent().next().show().siblings().hide();
					for (let i = 0; i < data.data.length; i++) {
						var li = $(`<p>${data.data[i].name}<em>${data.data[i].code}</em></p>`);
						li.appendTo(this_.parent().next());
					}
				}
			})
		} else if (ix == 3) {
			this_.parent().nextAll().empty();
			new ajax({
				url: 'area/SmallCommunity/getSmallCommunity.do',
				type: 'post',
				contentType: 'application/json;charset=utf-8',
				dataType: 'json',
				data: JSON.stringify({
					areaCode: parent
				}),
				success: function(data) {
					if (data.respCode != "S") {
						return;
					}
					for (let i = 0; i < data.data.length; i++) {
						var li = $(`<p>${data.data[i].name}<em>${data.data[i].smallCommunityId}</em><span>${data.data[i].areaCode}</span></p>`);
						li.appendTo(this_.parent().next());
					}
					this_.parent().next().show().siblings().hide();
				},
			})
		} else if (ix == 4) {
			var all_parent = this_.children().eq(1).text()
			$(".Supermarket_con").children().eq(1).children().empty();
			new ajax({
				url: 'area/Supermarket/getSupermarket.do',
				type: 'post',
				contentType: 'application/json;charset=utf-8',
				dataType: 'json',
				data: JSON.stringify({
					areaCode: all_parent
				}),
				success: function(data) {
					if (data.respCode != "S") {
						return;
					}
					for (let i = 0; i < data.data.length; i++) {
						var li = $(`<p>${data.data[i].name}<em>${data.data[i].supermarketId}</em></p>`);
						li.appendTo(".Supermarket_xuan div");
					}
				},
			})
			address_con.children().animate({
					top: "33.35rem"
				},
				function() {
					address_con.hide().children().eq(1).children().empty().hide().eq(0).show().end().end().end().eq(0).children().text("");
				});
			addressOne = all_parent;
			var resss = address_view.children().eq(0).text() + address_view.children().eq(1).text() + address_view.children().eq(2).text() + address_view.children().eq(3).text() + address_view.children().eq(4).text();
			$trigger1.val(resss);
			error_ress = false;
			$(".Supermarket_con").show().children().animate({
				top: 0
			});
		}

	});
	//选择超市
	$(".Supermarket_xuan").delegate('p', 'click', function() {
		supermarketId = $(this).children().text();
		var contstr2 = $(this).contents().filter(function(index, content) {
			return content.nodeType === 3;
		}).text();
		$("#Supermarket").val(contstr2);
		$(".Supermarket_con").children().animate({
				top: "33.35rem"
			},
			function() {
				$(".Supermarket_con").hide();
			});
	});
	//返回地址选择
	address_view.delegate('p', 'click', function() {
		var ix = $(this).nextAll().text("").end().index();
		address_xuan.children().eq(ix).show().nextAll().hide();
	});


	//提示弹框
	function toolTip_box(msg, go) {
		msg ? msg : msg = "未知错误";
		$pop10.children().text(msg).end().show(function() {
			const this_ = $(this);
			setTimeout(function() {
				this_.hide();
				go ? window.location.href = "../" : null;
			}, 1200);
		});
	}
	$pop10.click(function() {
		$(this).hide();
	});

	function tipsBox(text) {
        let dialog = $('.dialog')
        $('.dialog-content').html(text)
        dialog.css('display', 'block')
        let btn = $('.dialog-ok')
        btn.on('click', function () {
            dialog.css('display', 'none')
            window.location.href = '../my/member_info_authentication.html'
        })
    }
})
